<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<!--<el-form-item>
					<el-input v-model="filters.name" placeholder="产品名称"></el-input>
				</el-form-item>
				 <el-form-item>
					<el-button type="primary" v-on:click="getUsers">查询</el-button>
				</el-form-item> -->
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="datas" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<!-- <el-table-column type="selection" width="55">
			</el-table-column> -->
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="title" label="名称" width="120" sortable>
			</el-table-column>
			<!-- <el-table-column prop="sex" label="图片" width="100" :formatter="formatSex" sortable>
			</el-table-column> -->
			<el-table-column prop="rank" label="热度" width="100" sortable>
			</el-table-column>
      <el-table-column prop="desp" label="描述" min-width="180" sortable>
			</el-table-column>
		<!--	<el-table-column prop="rate" label="利率"  width="120" sortable>
			</el-table-column>
      	<el-table-column prop="max" label="最高可借" min-width="180" sortable>
			</el-table-column>
			<el-table-column prop="isAutoApproval" label="是否自动审批" :formatter="formatIsAutoApproval" min-width="180" sortable>
			</el-table-column>
      <el-table-column prop="isCheckCredit" label="是否查征信" :formatter="formatIsCheckCredit" min-width="180" sortable>
			</el-table-column>
			<el-table-column prop="isNew" label="是否是新品" :formatter="formatIsNew" min-width="180" sortable>
			</el-table-column>
      <el-table-column prop="isMaxLowFee" label="是否大额低息" :formatter="formatIsMaxLowFee" min-width="180" sortable>
			</el-table-column>-->
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<!-- <el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
			</el-pagination>
		</el-col> -->

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="产品名称" prop="title">
					<el-input v-model="editForm.title" auto-complete="off"></el-input>
				</el-form-item>

        	<!--<el-form-item label="图片地址">
					<el-input v-model="editForm.imageUrl"></el-input>
				</el-form-item>-->

        <el-form-item label="上传图片">
           <el-upload  class="avatar-uploader" action="http://47.101.53.90:80/api/imageUpload"
                    :show-file-list="false"
                    :on-success="editHandleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                 <img v-if="editForm.imageUrl" :src="editForm.imageUrl" style="width:160px;height:100px;" class="avatar">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
 

        <el-form-item label="热度">
					<el-input-number v-model="editForm.rank" :min="0" ></el-input-number>
				</el-form-item>

			<!--	<el-form-item label="利率">
             <el-input v-model="editForm.rate" @blur="formatEditFix(editForm.rate)"></el-input>
				</el-form-item>

         <el-form-item label="最高可借">
					<el-input-number v-model="editForm.max" :min="0" ></el-input-number>
				</el-form-item>

         <el-form-item>
				    <el-checkbox v-model="editForm.isAutoApproval" :false-label="0" :true-label="1" >是否自动审批</el-checkbox>
					<el-checkbox v-model="editForm.isNew" :false-label="0" :true-label="1" >是否新品</el-checkbox>
					<el-checkbox v-model="editForm.isMaxLowFee" :false-label="0" :true-label="1" >是否大额低息</el-checkbox>
					<el-checkbox v-model="editForm.isCheckCredit" :false-label="0" :true-label="1" >是否查征信</el-checkbox>
				</el-form-item>-->
				
        <el-form-item label="描述（建议15个字以内）">
					<el-input v-model="editForm.desp"></el-input>
				</el-form-item>
				<el-form-item label="跳转网页地址">
					<el-input v-model="editForm.webUrl"></el-input>
				</el-form-item> 
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="产品名称" prop="title">
					<el-input v-model="addForm.title" auto-complete="off"></el-input>
				</el-form-item>
			
        <!--<el-form-item label="图片地址">
					<el-input v-model="addForm.imageUrl"></el-input>
				</el-form-item>-->
        <el-form-item label="上传图片">
           <el-upload  class="avatar-uploader" action="http://47.101.53.90:80/api/imageUpload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                 <img v-if="addForm.imageUrl" :src="addForm.imageUrl" style="width:160px;height:100px;" class="avatar">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
       
          <el-form-item label="热度">
					<el-input-number v-model="addForm.rank" :min="0" ></el-input-number>
				</el-form-item>

		<!--		<el-form-item label="利率">
             <el-input v-model="addForm.rate" @blur="formatFix(addForm.rate)"></el-input>
				</el-form-item>

         <el-form-item label="最高可借">
					<el-input-number v-model="addForm.max" :min="0" ></el-input-number>
				</el-form-item>

        <el-form-item>
				  <el-checkbox v-model="addForm.isAutoApproval" :false-label="0" :true-label="1" >是否自动审批</el-checkbox>
					<el-checkbox v-model="addForm.isNew" :false-label="0" :true-label="1" >是否新品</el-checkbox>
					<el-checkbox v-model="addForm.isMaxLowFee" :false-label="0" :true-label="1" >是否大额低息</el-checkbox>
					<el-checkbox v-model="addForm.isCheckCredit" :false-label="0" :true-label="1" >是否查征信</el-checkbox>
				</el-form-item>-->
          <el-form-item label="描述（建议15个字以内）">
					<el-input v-model="addForm.desp"></el-input>
				</el-form-item>
				<el-form-item label="跳转网页地址">
					<el-input v-model="addForm.webUrl"></el-input>
				</el-form-item> 
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
import util from "../../common/js/util";
//import NProgress from 'nprogress'
import {
  getUserListPage,
  removeUser,
  batchRemoveUser,
  editUser,
  addUser
} from "../../api/api";
import translatorApi from "../../api/TranslatorApi";
import Toast from "../../util/Toast";
export default {
  created: function() {
    this.bannerType = "2";
  },
  data() {
    return {
      filters: {
        name: ""
      },
      bannerType: "2",
      datas: [],
      total: 0,
      page: 1,
      listLoading: false,
      sels: [], //列表选中列

      editFormVisible: false, //编辑界面是否显示
      editLoading: false,
      editFormRules: {
        title: [{ required: true, message: "请输入产品名称", trigger: "blur" }]
      },
      //编辑界面数据
      editForm: {
        id: 0,
        type: 2,
        title: "",
        rank: 0,
        rate: 0.0,
        isAutoApproval: 0,
        max: 0,
        isNew: 0,
        isMaxLowFee: 0,
        isCheckCredit: 0,
        desp: "",
        imageUrl: "",
        webUrl: ""
      },

      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        title: [{ required: true, message: "请输入姓名", trigger: "blur" }]
      },
      //新增界面数据
      addForm: {
        type: 2,
        title: "",
        rank: 1,
        rate: 0,
        max: 0,
        isAutoApproval: 0,
        isNew: 0,
        isMaxLowFee:0,
        isCheckCredit: 0,
        desp: "",
        imageUrl: "",
        webUrl: ""
      }
    };
  },
  methods: {
  handleAvatarSuccess(res, file) {
   this.addForm.imageUrl = res.data.imgUrl.split('?')[0]; 
   //this.addForm.imageUrl = URL.createObjectURL(file.raw); 
   }, 
   editHandleAvatarSuccess(res, file) {
   this.editForm.imageUrl = res.data.imgUrl.split('?')[0]; 

   //this.editForm.imageUrl = URL.createObjectURL(file.raw); 
   }, 
   beforeAvatarUpload(file) {  
     const isJPG = (file.type === 'image/jpeg'||file.type==="image/png"); 
     const isLt2M = file.size / 1024 / 1024 < 2; 
     if (!isJPG) { this.$message.error('只能上jpg或png图片格式!'); }
      if (!isLt2M) { this.$message.error('上传图片大小不能超过 2MB!'); }
       return isJPG && isLt2M; 
       },

    //验证数字
    formatFix:function(rote){ 
        var re = /^(-?\d+)(\.\d+)?$/
        if(re.test(rote)){
             this.addForm.rate = rote;
        }else{
            this.addForm.rate = parseFloat("0").toFixed(2);
        }     
    },
      formatEditFix:function(rote){ 
        var re = /^(-?\d+)(\.\d+)?$/
        if(re.test(rote)){
             this.editForm.rate = rote;
        }else{
            this.editForm.rate = parseFloat("0").toFixed(2);
        }     
    },

    //数字显示转换
    formatIsNew: function(row, column) {
      return row.isNew == 1 ? "是" : row.isNew == 0 ? "否" : "未知";
    },
    formatIsAutoApproval: function(row, column) {
      return row.isAutoApproval == 1 ? "是" : row.isAutoApproval == 0 ? "否" : "未知";
    },
    formatIsMaxLowFee: function(row, column) {
      return row.isMaxLowFee == 1 ? "是" : row.isMaxLowFee == 0 ? "否" : "未知";
    },
    formatIsCheckCredit: function(row, column) {
      return row.isCheckCredit == 1 ? "是" : row.isCheckCredit == 0 ? "否" : "未知";
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getBannerDatas();
    },

    //获取数据
     getBannerDatas() {

       var _this=this;
       this.listLoading = true;

       translatorApi.requestBannerAll(this.bannerType, function callback(
       response
       ) {
         _this.listLoading = false;
         if (response.isSuccess()) {
           _this.datas = response.data;
         } else {
           Toast.show(response.message);
         }
       });
     },

    // //获取用户列表
    /*getBannerDatas() {
      let para = {
        page: this.page,
        name: this.filters.name
      };
      this.listLoading = true;
      //NProgress.start();
      getUserListPage(para).then(res => {
        this.total = res.data.total;
        this.datas = res.data.users;
        this.listLoading = false;
        //NProgress.done();
      });
    },*/
    //删除
    handleDel: function(index, row) {
      this.$confirm("确认删除该记录吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          var _this = this;
          _this.listLoading = true;
    
          translatorApi.requestDeleteBanner(
            row.id,
            function callback(response) {
    
            _this.listLoading = false;
             if (response.isSuccess()) {
                _this.getBannerDatas();
             }
            Toast.show(response.message);
              //self.$router.replace("/editMainPage");
            }
          );

          /* this.listLoading = true;
          //NProgress.start();
          let para = { id: row.id };
          removeUser(para).then(res => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getBannerDatas();
          });*/
        })
        .catch(() => {});
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function() {
      this.addFormVisible = true;
    },
    //编辑
    editSubmit: function() {
      var _this = this;

      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            _this.editLoading = true;

            //_this.addForm['type']='1';
            translatorApi.requestUpdateBanner(_this.editForm, function callback(
              response
            ) {
              _this.editLoading = false;
              _this.editFormVisible = false;
              if (response.isSuccess()) {
                // this.$refs["addForm"].resetFields();
                _this.getBannerDatas();
              } 
              Toast.show(response.message);
              //_this.editLoading = false;
            });

            // this.editLoading = true;
            // //NProgress.start();
            // let para = Object.assign({}, this.editForm);
            // para.birth =
            //   !para.birth || para.birth == ""
            //     ? ""
            //     : util.formatDate.format(new Date(para.birth), "yyyy-MM-dd");
            // editUser(para).then(res => {
            //   this.editLoading = false;
            //   //NProgress.done();
            //   this.$message({
            //     message: "提交成功",
            //     type: "success"
            //   });
            //   this.$refs["editForm"].resetFields();
            //   this.editFormVisible = false;
            //   this.getBannerDatas();
            // });
          });
        }
      });
    },
    //新增
    addSubmit: function() {
      var _this = this;
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            _this.addLoading = true;

            _this.addForm["type"] = _this.bannerType;
            translatorApi.requestAddBanner(_this.addForm, function callback(
              response
            ) {
              _this.addLoading = false;
              _this.addFormVisible = false;
              if (response.isSuccess()) {
                _this.getBannerDatas();
              } 
              Toast.show(response.message);
            });

            // //NProgress.start();
            // let para = Object.assign({}, this.addForm);
            // para.birth =
            //   !para.birth || para.birth == ""
            //     ? ""
            //     : util.formatDate.format(new Date(para.birth), "yyyy-MM-dd");
            // addUser(para).then(res => {
            //   this.addLoading = false;
            //   //NProgress.done();
            //   this.$message({
            //     message: "提交成功",
            //     type: "success"
            //   });
            //   this.$refs["addForm"].resetFields();
            //   this.addFormVisible = false;
            //   this.getBannerDatas();
            // });
          });
        }
      });
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function() {
      var ids = this.sels.map(item => item.id).toString();
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          //NProgress.start();
          let para = { ids: ids };
          batchRemoveUser(para).then(res => {
            this.listLoading = false;
            //NProgress.done();
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getBannerDatas();
          });
        })
        .catch(() => {});
    }
  },
  created() {
    //	alert("ccc");
  },
  mounted() {
    this.getBannerDatas();
  }
};
</script>

<style scoped>
</style>